package org.yds.quality.function;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorJavaType;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SumIfDefectFunction extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject listObj, AviatorObject conditionObj) {
        List<?> list = (List<?>) listObj.getValue(env);
        String condition = (String) conditionObj.getValue(env);

        long total = 0;
        for (Object item : list) {
            if (item instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) item;
                // 将当前 item 的 size 放入局部环境
                Map<String, Object> localEnv = new HashMap<>(env);
                localEnv.put("size", map.get("size"));

                // 执行逻辑表达式
                boolean match = (boolean) AviatorEvaluator.execute(condition, localEnv);
                if (match) {
                    total ++;
                }
            }
        }

        return AviatorLong.valueOf(total);
    }

    @Override
    public String getName() {
        return "SumIfDefect";
    }
}